package com.task.manage.system.controller;

import java.util.List;

import com.task.manage.common.exception.ServiceException;
import com.task.manage.common.utils.StringUtils;
import com.task.manage.common.utils.spring.SpringUtils;
import com.task.manage.system.domain.MerchantInfo;
import com.task.manage.system.service.IMerchantInfoService;
import com.task.manage.web.controller.demo.domain.TaskModel;
import com.task.manage.web.controller.demo.domain.UserOperateModel;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.task.manage.common.annotation.Log;
import com.task.manage.common.enums.BusinessType;
import com.task.manage.system.domain.MerchantTask;
import com.task.manage.system.service.IMerchantTaskService;
import com.task.manage.common.core.controller.BaseController;
import com.task.manage.common.core.domain.AjaxResult;
import com.task.manage.common.utils.poi.ExcelUtil;
import com.task.manage.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 商家任务Controller
 *
 * @author ruoyi
 * @date 2024-05-09
 */
@Controller
@RequestMapping("/system/task")
public class MerchantTaskController extends BaseController {
    private String prefix = "system/task";

    @Resource
    private IMerchantTaskService merchantTaskService;

    @Autowired
    private IMerchantInfoService merchantInfoService;

    @RequiresPermissions("system:task:view")
    @GetMapping()
    public String task() {
        return prefix + "/task";
    }

    /**
     * 查询商家任务列表
     */
    @RequiresPermissions("system:task:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(MerchantTask merchantTask) {
        startPage();
        List<MerchantTask> list = merchantTaskService.selectMerchantTaskList(merchantTask);
        return getDataTable(list);
    }

    /**
     * 导入数据
     */
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<TaskModel> util = new ExcelUtil<TaskModel>(TaskModel.class);
        List<TaskModel> taskList = util.importExcel(file.getInputStream());
        String message = importMerchant(taskList, updateSupport);
        return AjaxResult.success(message);
    }

    /**
     * 导入商家数据
     * @param taskList
     * @param updateSupport
     * @return
     */
    private String importMerchant(List<TaskModel> taskList, boolean updateSupport) {
        if (StringUtils.isNull(taskList) || taskList.size() == 0) {
            throw new ServiceException("导入商家任务数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (TaskModel task : taskList){
            try {
                MerchantTask merchantTask=new MerchantTask();
                BeanUtils.copyProperties(task,merchantTask);
                //这里要通过商户名称去找商户id
                String mercName= task.getMercName().trim();
                if(StringUtils.isEmpty(mercName)){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、商户名称不能为空");
                    continue;
                }
                MerchantInfo merchantInfo=new MerchantInfo();
                merchantInfo.setMercName(mercName);
                List<MerchantInfo> merchantInfoList=   merchantInfoService.selectMerchantInfoList(merchantInfo);
                if(CollectionUtils.isEmpty(merchantInfoList)){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、没有查到商户信息");
                    continue;
                }
                MerchantInfo oldMerchant=merchantInfoList.get(0);
                merchantTask.setMercId(oldMerchant.getId());
                merchantTask.setTaskCounts(merchantTask.getTaskAllCounts());
                merchantTaskService.insertMerchantTask(merchantTask);
                successNum++;
                successMsg.append("<br/>" + successNum + "、店铺 " + merchantTask.getStoreName() + " 导入成功");
            }catch (Exception e){
                failureNum++;
                String msg = "<br/>" + failureNum + "、店铺名称 " + task.getStoreName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }

        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 下载模板
     */
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<TaskModel> util = new ExcelUtil<TaskModel>(TaskModel.class);
        return util.importTemplateExcel("任务订单数据");
    }

    /**
     * 导出商家任务列表
     */
    @RequiresPermissions("system:task:export")
    @Log(title = "商家任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(MerchantTask merchantTask) {
        List<MerchantTask> list = merchantTaskService.selectMerchantTaskList(merchantTask);
        ExcelUtil<MerchantTask> util = new ExcelUtil<MerchantTask>(MerchantTask.class);
        return util.exportExcel(list, "商家任务数据");
    }

    /**
     * 新增商家任务
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        mmap.put("mercList", merchantInfoService.selectAllMerchantInfoList());
        return prefix + "/add";
    }

    /**
     * 新增保存商家任务
     */
    @RequiresPermissions("system:task:add")
    @Log(title = "商家任务", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(MerchantTask merchantTask) {
        //新增的时候总任务数=剩余任务数
        merchantTask.setTaskCounts(merchantTask.getTaskAllCounts());
        return toAjax(merchantTaskService.insertMerchantTask(merchantTask));
    }

    /**
     * 修改商家任务
     */
    @RequiresPermissions("system:task:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        MerchantTask merchantTask = merchantTaskService.selectMerchantTaskById(id);
        mmap.put("mercList", merchantInfoService.selectAllMerchantInfoList());
        mmap.put("merchantTask", merchantTask);
        return prefix + "/edit";
    }

    /**
     * 修改保存商家任务
     */
    @RequiresPermissions("system:task:edit")
    @Log(title = "商家任务", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(MerchantTask merchantTask) {
        Long id=merchantTask.getId();
        MerchantTask oldMerchantTask=merchantTaskService.selectMerchantTaskById(id);
        Long remainTask=0L;
        //计算现在的任务剩余数量
        if(oldMerchantTask.getTaskAllCounts()==null){
          if(merchantTask.getTaskAllCounts()-oldMerchantTask.getTaskCounts()<=0){
              //任务总数的设置小于剩余任务数的情况 应将任务总数和剩余任务数都设置为任务总数
              BeanUtils.copyProperties(merchantTask,oldMerchantTask);
              oldMerchantTask.setTaskCounts(merchantTask.getTaskAllCounts());
              oldMerchantTask.setTaskAllCounts(merchantTask.getTaskAllCounts());
              return toAjax(merchantTaskService.updateMerchantTask(oldMerchantTask));
          }else {
              //任务总数大于剩余任务数的情况
              remainTask=oldMerchantTask.getTaskCounts();
          }
        }else{
            if(merchantTask.getTaskAllCounts()<=oldMerchantTask.getTaskCounts()){
                //任务总数小于当前剩余任务数 BeanUtils.copyProperties(merchantTask,oldMerchantTask); BeanUtils.copyProperties(oldMerchantTask,merchantTask);
                BeanUtils.copyProperties(merchantTask,oldMerchantTask);
                oldMerchantTask.setTaskCounts(merchantTask.getTaskAllCounts());
                oldMerchantTask.setTaskAllCounts(merchantTask.getTaskAllCounts());
                return toAjax(merchantTaskService.updateMerchantTask(oldMerchantTask));
            }else {
                //任务总数大于当前剩余任务数
                remainTask=merchantTask.getTaskAllCounts()-oldMerchantTask.getTaskAllCounts()+oldMerchantTask.getTaskCounts();
            }
        }
        BeanUtils.copyProperties(merchantTask,oldMerchantTask);
        oldMerchantTask.setTaskCounts(remainTask);
        oldMerchantTask.setTaskAllCounts(merchantTask.getTaskAllCounts());
        return toAjax(merchantTaskService.updateMerchantTask(oldMerchantTask));
    }

    /**
     * 删除商家任务
     */
    @RequiresPermissions("system:task:remove")
    @Log(title = "商家任务", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        merchantTaskService.deleteTaskInfo(ids);
        return  AjaxResult.success();
    }

    /**
     * 商家任务产品链接防重复提交
     * @return
     */
    @PostMapping("/checkProductLinkUnique")
    @ResponseBody
    private boolean checkProductLinkUnique(MerchantTask merchantTask){
        Long id = StringUtils.isNull(merchantTask.getId()) ? -1L : merchantTask.getId();
        IMerchantTaskService  taskService= SpringUtils.getBean(IMerchantTaskService.class);
        List<MerchantTask> oldMerchantTask=taskService.selectByProduct(merchantTask.getProductLink());
        if(!CollectionUtils.isEmpty(oldMerchantTask) ){
            boolean containsId= oldMerchantTask.stream().anyMatch(task->task.getId().longValue()!=id.longValue());
            if(containsId){
                return false;
            }
        }
        return true;
    }
}
